package com.sw.passbook.merchants.interceptor;


import com.sw.passbook.merchants.constant.CommonConstants;
import com.sw.passbook.merchants.sercurity.AccessTokenContext;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Desc: 权限拦截器 拦截所有http请求
 * @Author: wusonghe
 * @Date: 2018/11/27 17:36
 */
@Component
public class AuthCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader(CommonConstants.TOKEN_STRING);
        if (StringUtils.isEmpty(token)) {
            throw new Exception("Header中缺少 "  + CommonConstants.TOKEN_STRING);
        }

        // 临时
        if (!token.equals(CommonConstants.TEMP_REQUEST_TOKEN_NAME)){
            throw new Exception("Header中 "  + CommonConstants.TOKEN_STRING + "错误");
        }
        AccessTokenContext.setToken(token);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        //抛出异常处理

        //清除脏数据
        AccessTokenContext.clearAccessKey();
    }
}
